package com.stitch.dcslock.config;

import com.stitch.dcslock.properties.RedisLockProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Redis 分布式锁自动配置类
 * - 负责创建 RedissonClient，并自动读取 redis.lock 配置
 * - 只有当 redis.lock.enabled=true 时才会生效
 */
@Configuration
@EnableConfigurationProperties(RedisLockProperties.class)
@ConditionalOnProperty(name = "redis.lock.enabled", havingValue = "true", matchIfMissing = true)
public class RedisLockAutoConfiguration {

    private final RedisLockProperties properties;

    public RedisLockAutoConfiguration(RedisLockProperties properties) {
        this.properties = properties;
    }

    /**
     * 创建 RedissonClient Bean
     * - 读取 Redis 配置并初始化 Redisson
     */
    @Bean
    @ConditionalOnMissingBean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress(properties.getAddress())
                .setPassword(properties.getPassword().isEmpty() ? null : properties.getPassword())
                .setDatabase(properties.getDatabase());
        config.setCodec(new JsonJacksonCodec());
        return Redisson.create(config);
    }
}
